package io.xccit.system.util;

import io.xccit.model.system.SysMenu;
import java.util.ArrayList;
import java.util.List;

/**
 * @author CH_ywx
 * @date 2023-06-26
 * @description 构建树形菜单工具
 */
public class MenuItemHelper {

    /**
     * 使用树形结构构建菜单
     * @param sysMenuList 所有菜单
     * @return 构建树形结构后的所有菜单
     */
    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
        List<SysMenu> treeResult = new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            if (sysMenu.getParentId() == 0){
                treeResult.add(findChildren(sysMenu,sysMenuList));
            }
        }
        return treeResult;
    }

    /**
     * 递归查找父菜单的子菜单
     * @param sysMenu 父菜单
     * @param sysMenuList 所有菜单
     * @return 父菜单
     */
    private static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> sysMenuList) {
        if (sysMenu.getChildren() == null){
            sysMenu.setChildren(new ArrayList<>());
        }
        for (SysMenu menu : sysMenuList) {
            if (menu.getParentId() == sysMenu.getId()){
                sysMenu.getChildren().add(findChildren(menu,sysMenuList));
            }
        }
        return sysMenu;
    }
}
